package net.yla.smartbus.module.ba.group.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.vip.vjtools.vjkit.collection.ListUtil;
import com.vip.vjtools.vjkit.mapper.BeanMapper;
import lombok.SneakyThrows;
import net.yla.smartbus.core.api.RequestCode;
import net.yla.smartbus.core.base.PageBean;
import net.yla.smartbus.core.exception.AppException;
import net.yla.smartbus.core.util.DtoUtils;
import net.yla.smartbus.core.util.data.DataTypeUtil;
import net.yla.smartbus.module.ba.employee.entity.EmployeeDO;
import net.yla.smartbus.module.ba.employee.mapper.EmployeeMapper;
import net.yla.smartbus.module.ba.group.dto.GroupPages;
import net.yla.smartbus.module.ba.group.entity.CompanyDO;
import net.yla.smartbus.module.ba.group.entity.GroupEntity;
import net.yla.smartbus.module.ba.group.entity.GroupTreeDO;
import net.yla.smartbus.module.ba.group.form.CountParams;
import net.yla.smartbus.module.ba.group.form.GroupForm;
import net.yla.smartbus.module.ba.group.mapper.GroupMapper;
import net.yla.smartbus.module.ba.group.query.CompanyQuery;
import net.yla.smartbus.module.ba.group.query.GroupQuery;
import net.yla.smartbus.module.ba.group.service.GroupService;
import net.yla.smartbus.module.ba.group.util.DateUtil;
import net.yla.smartbus.module.ba.group.util.Spelling;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @description:
 * @author: Yee
 * @date: 2021/6/16 14:33
 */
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 查询机构信息
     *
     * @param query
     * @return
     */
    @Override
    public PageBean<GroupForm> getGroups(GroupQuery query) {

        List<CompanyDO> groups = groupMapper.getGroups(query);
        PageHelper.startPage(query.getPageNum(), query.getPageSize(), "dutieId desc");
        List<GroupForm> groupForms = new ArrayList<>(groups.size());

        for (CompanyDO groupDO : groups) {
            GroupForm groupForm = new GroupForm();
            //查询人员数
            List<EmployeeDO> byGroupId = employeeMapper.findByGroupId(groupDO.getGroupId());
            groupForm.setPersonNum(byGroupId.size());
            //查询父公司
            Integer parentId = groupDO.getParentId();
            if (parentId == 0 || parentId == null) {
                groupForm.setGroupId(groupDO.getGroupId());
                groupForm.setParentName(groupDO.getName());
            } else {
                String parentName = groupMapper.getParentName(groupDO.getParentId());
                groupForm.setParentName(parentName);
                Integer gParentId = groupMapper.getGParentId(groupDO.getGroupId());
                groupForm.setGroupId(gParentId);
            }

            groupForm.setCompanyId(groupDO.getCompanyId());
            groupForm.setName(groupDO.getName());
            groupForm.setParentId(parentId);
            groupForm.setAddress(groupDO.getAddress());
            groupForm.setTel(groupDO.getTel());
            //查询车辆数
            Integer carNum = groupMapper.getCarNum(groupDO.getGroupId());
            groupForm.setCarNum(carNum);
            //查询设备数
            Integer deviceNum = groupMapper.getDeviceNum(groupDO.getGroupId());
            groupForm.setDeviceNum(deviceNum);
            groupForm.setRegAddress(groupDO.getRegAddress());
            groupForm.setRegTime(groupDO.getRegTime());
            groupForm.setRegCapital(groupDO.getRegCapital());
            groupForm.setOrgCode(groupDO.getOrgCode());
            groupForm.setCreditCode(groupDO.getCreditCode());
            groupForm.setLicenseCode(groupDO.getLicenseCode());
            groupForm.setTaxpayerCode(groupDO.getTaxpayerCode());
            groupForm.setScopeDescribe(groupDO.getScopeDescribe());
            groupForm.setEconomy(groupDO.getEconomy());
            groupForm.setFax(groupDO.getFax());
            groupForm.setEmail(groupDO.getEmail());
            groupForm.setLegalPersonName(groupDO.getLegalPersonName());
            groupForm.setLegalPersonTel(groupDO.getLegalPersonTel());
            groupForms.add(groupForm);
        }
        return new PageBean<>(groupForms, query.getPageNum(), query.getPageSize(), groupForms.size());
    }

    /**
     * 级联菜单---分组树
     *
     * @return
     */

    @Override
    public GroupTreeDO trees() {
        CountParams countParams = new CountParams();
        List<GroupPages> list = this.querys(countParams);
        if (ListUtil.isNotEmpty(list)) {
            return this.getCascader(list);
        } else {
            return new GroupTreeDO(new ArrayList<>());
        }
    }

    /**
     * 逻辑删除职务信息
     *
     * @param query
     * @return
     */
    @Override
    public int deleteGroups(GroupQuery query) {

        //逻辑删除公司信息
        Integer groupId = groupMapper.getGroupId1(query.getCompanyId());
        Integer i1 = groupMapper.updateCompany(query.getCompanyId());
        Integer i2 = groupMapper.updateGroup(groupId);
        if (i1 < 0 ){
            groupMapper.updateGroup1(groupId);
            throw new AppException("删除机构失败", RequestCode.forbid_error);
        }else if(i2 < 0){
            //逻辑删除分组信息
            groupMapper.updateCompanies(query.getCompanyId());
            throw new AppException("删除机构失败", RequestCode.forbid_error);
        }
        return 1;
    }

    /**
     * 编辑机构信息
     *
     * @param query
     * @return
     */
    @SneakyThrows
    @Override
    public int editCompany(CompanyQuery query) {

        if (query.getName() == null) {
            throw new AppException("机构名不能为空", RequestCode.forbid_error);
        }
        GroupEntity groupEntity = new GroupEntity();
        CompanyDO companyDO = new CompanyDO();
        groupEntity.setParentId(query.getGroupId());
        groupEntity.setName(query.getName());
        groupEntity.setPinyin(Spelling.pinyin(query.getName()));
        groupEntity.setAbbr(Spelling.abbr(query.getName()));
        companyDO.setName(query.getName());
        companyDO.setAddress(query.getAddress());
        companyDO.setTel(query.getTel());
        companyDO.setRegAddress(query.getRegAddress());
        companyDO.setRegCapital(query.getRegCapital());
        companyDO.setRegTime(query.getRegTime());
        companyDO.setOrgCode(query.getOrgCode());
        companyDO.setCreditCode(query.getCreditCode());
        companyDO.setLicenseCode(query.getLicenseCode());
        companyDO.setTaxpayerCode(query.getTaxpayerCode());
        companyDO.setScopeDescribe(query.getScopeDescribe());
        companyDO.setEconomy(query.getEconomy());
        companyDO.setFax(query.getFax());
        companyDO.setEmail(query.getEmail());
        companyDO.setLegalPersonName(query.getLegalPersonName());
        companyDO.setLegalPersonTel(query.getLegalPersonTel());

        //添加or修改
        if (query.getCompanyId() == null) {
            Integer parentId = query.getGroupId();
            if (parentId == null) {
                groupEntity.setQualifiedName(query.getName());
                groupEntity.setLevel(0);
            } else {
                String qualifiedName = groupMapper.view(query.getGroupId()).getQualifiedName();
                groupEntity.setQualifiedName(qualifiedName + "/" + query.getName());
                Integer level = groupMapper.view(query.getGroupId()).getLevel();
                groupEntity.setLevel(level + 1);
                parentId = query.getGroupId();
                List<Integer> list = new ArrayList<>();
                list.add(parentId);
                while (parentId == 0) {
                    parentId = groupMapper.getParentId(parentId);
                    list.add(parentId);
                }
                Collections.reverse(list);
                Integer[] one = list.toArray(new Integer[list.size()]);
                byte[] buffer = DataTypeUtil.getByteArray(one);
                groupEntity.setParents(buffer);
            }
            Integer i2 = groupMapper.insertGroup(groupEntity);
            Integer groupId3 = groupEntity.getGroupId();
            if (i2 < 0) {
                throw new AppException("新增机构失败", RequestCode.forbid_error);
            } else {
                if (parentId != null) {
                    GroupEntity groupChildren = groupMapper.getGroupChildren(parentId);
                    Integer parentId1 = groupChildren.getParentId();
                    if (parentId1 == 0) {
                        Integer groupId2 = groupChildren.getGroupId();
                        byte[] bytes = DataTypeUtil.getByteBy32Int(groupId2);
                        int i = groupMapper.updateChildren(groupId2, bytes);
                    } else {
                        while (parentId == 0) {
                            GroupEntity groupChildren1 = groupMapper.getGroupChildren(parentId);
                            parentId = groupChildren1.getParentId();
                            byte[] children = groupMapper.getGroupChildren(parentId).getChildren();
                            int[] intArray1 = DataTypeUtil.getIntArray(children);
                            int[] newChildren = Arrays.copyOf(intArray1, intArray1.length + 1);
                            newChildren[intArray1.length] = groupId3;
                            byte[] byteArray = DataTypeUtil.getByteArray(newChildren);
                            groupMapper.updateChildren(groupChildren1.getGroupId(), byteArray);
                        }
                    }
                }

                Integer CP = groupMapper.getParentId(query.getGroupId());
                companyDO.setCompanyId(query.getCompanyId());
                companyDO.setParentId(CP);
                companyDO.setGroupId(groupId3);

                Integer integer = groupMapper.insertCompany(companyDO);
                if (integer < 0) {
                    int i = groupMapper.delGroup(groupId3);
                    throw new AppException("新增机构失败", RequestCode.forbid_error);
                }
            }
        } else {
            GroupQuery groupQuery = new GroupQuery();
            groupQuery.setCompanyId(query.getCompanyId());
            List<CompanyDO> groups = groupMapper.getGroups(groupQuery);
            //查询父机构
            Integer CP = groupMapper.getParentId(query.getGroupId());
            companyDO.setCompanyId(query.getCompanyId());
            companyDO.setParentId(CP);
            companyDO.setGroupId(groups.get(0).getGroupId());
            int i1 = groupMapper.updateCompanys(companyDO);
            groupEntity.setGroupId(companyDO.getGroupId());
            if (i1 < 0) {
                throw new AppException("修改机构失败", RequestCode.forbid_error);
            } else {
                int i = groupMapper.updateGroups(groupEntity);
                if (i < 0) {
                    int i2 = groupMapper.updateCompanys(groups.get(0));
                    throw new AppException("修改机构失败", RequestCode.forbid_error);
                }
            }
        }
        return 0;
    }


    public List<GroupPages> querys(CountParams countParam) {

        if (countParam.getVisible() == null) {
            countParam.setVisible(0);

        } else {
            Integer visible = countParam.getVisible();

            //仅显示已逻辑删除记录
            if (visible == 2) {
                countParam.setVisible(-1);

                //显示正常和已逻辑删除记录
            } else if (visible == 3) {
                countParam.setVisible(null);

                //仅显示正常记录
            } else {
                countParam.setVisible(0);
            }

        }

        ArrayList<GroupPages> groupPages = new ArrayList<>();
        GroupPages groupPage = null;
        List<GroupEntity> query = groupMapper.query(countParam);
        for (int i = 0; i < query.size(); i++) {
            groupPage = new GroupPages();
            groupPage.setOrgId(query.get(i).getGroupId());
            groupPage.setFlag(query.get(i).getGroupId());
            groupPage.setLevel(query.get(i).getLevel());
            groupPage.setType(query.get(i).getGroupType());
            groupPage.setOrgName(query.get(i).getName());
            groupPage.setQualifiedName(query.get(i).getQualifiedName());
            groupPage.setPinyin(query.get(i).getPinyin());
            groupPage.setAbbr(query.get(i).getAbbr());
            groupPage.setLat(query.get(i).getLatitude());
            groupPage.setLng(query.get(i).getLongitude());
            groupPage.setParent(query.get(i).getParentId());
            if (query.get(i).getHidden() == -1) {
                groupPage.setHidden(true);
            } else {
                groupPage.setHidden(false);
            }
            groupPage.setSortOrder(query.get(i).getSortOrder());
            groupPage.setCreation(DateUtil.d_s(query.get(i).getCreationTime()));
            groupPage.setModify(DateUtil.d_s(query.get(i).getLastModifyTime()));

            List<EmployeeDO> employeeDOS = employeeMapper.findByGroupId(query.get(i).getGroupId());
            List<JSONObject> jsonObjects = new LinkedList<>();
            for (EmployeeDO employeeDO : employeeDOS) {
                JSONObject jsonObject = DtoUtils.asDtoJsonForOnly(employeeDO);
            }

            /*AccountsDO accountsDO=accountsMapper.selectByPrimaryKey(employeeDOS.getEmpId());

           /* groupPage.setId(accountsDO.getAccountId());*/

            groupPages.add(groupPage);

        }

        return groupPages;

    }

    /**
     * 获取分组树
     *
     * @return
     */
    public GroupTreeDO getCascader(List<GroupPages> list) {

        GroupTreeDO gTree = new GroupTreeDO();
        gTree.setChildren(new ArrayList<>());

        Map<Integer, GroupTreeDO> map = new HashMap<>();
        list.forEach(s -> map.put(s.getOrgId(), BeanMapper.map(s, GroupTreeDO.class)));

        Set<Map.Entry<Integer, GroupTreeDO>> set = map.entrySet();
        Iterator<Map.Entry<Integer, GroupTreeDO>> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, GroupTreeDO> entry = iterator.next();
            GroupTreeDO groupTree = entry.getValue();
            if (groupTree.getParent() == null || map.get(groupTree.getParent()) == null) {
                gTree.getChildren().add(groupTree);
            } else if (groupTree.getParent() != null) {
                if (map.get(groupTree.getParent()).getChildren() == null) {
                    map.get(groupTree.getParent()).setChildren(new ArrayList<>());
                }
                map.get(groupTree.getParent()).getChildren().add(groupTree);
            }
        }
        return gTree;
    }


    /**
     * 根据id 查询 分组
     *
     * @param groupId
     * @return
     */
    @Override
    public GroupEntity view(Integer groupId) {
        GroupEntity view = groupMapper.view(groupId);
        return view;
    }


}
